<?php

namespace app\common\behavior;

use think\Exception;
use think\Loader;
use think\Lang;

class Wish 
{
	/**
	 * 满足心愿后置操作
	 * @param  [type] &$data [description]
	 * @return [type]        [description]
	 */
    public function afterMeetWish(&$id)
    {
        try {
        	
        } catch (\Exception $e) {
        	
        }
    }

    /**
     * 心愿完成后操作
     * @param  [type] &$id [description]
     * @return [type]      [description]
     */
    public function afterCompleteWish(&$id)
    {
        # code...
    }

    public function afterCreateUserWish(&$wish_infos)
    {
        try {
            $notice_instance = \services\notices\Notice::instance();

            foreach ($wish_infos as $wish_info) {

                $where = [
                    'datetimes' => ['BETWEEN', [$wish_info['start_date'], $wish_info['end_date']]]
                ];

                $sub_user_id = Loader::model('Calendar')
                ->where($where)
                ->where(function($query){
                    $query->where(['trusts' => 1, 'shares' => 0])->whereOr(['orders' => 1]);
                })
                ->column('user_id');

                $user_ids = Loader::model('Calendar')->hasWhere('caravans', ['area' => $wish_info['region']])
                            ->where($where)
                            ->group('caravan_id')
                            ->having('sum(`orders`) = 0')
                            ->column('calendar.user_id');

                if ($user_ids) {
                    $user_ids = array_diff($user_ids, $sub_user_id);
                    if ($signs = Loader::model('Users')->where(['id' => ['in', $user_ids]])->column('sign')) {
                        $recipients['sign'] = $signs;
                    }
                }
            }

            if (isset($recipients)) {
                //发送通知信息
                $notice_instance->send($recipients, Lang::get('Wish to release'), Lang::get('Wish to release'));
            }
            
        } catch (\Exception $e) {}
    }
}